package com.myzl.coal.service.impl;

import cn.hutool.core.io.file.FileReader;
import com.alibaba.fastjson2.JSONObject;
import com.myzl.coal.service.AiShowService;
import com.myzl.coal.service.IPythonService;
import com.myzl.common.config.ImageRecognitionConfig;
import com.myzl.common.constant.CacheConstants;
import com.myzl.common.core.domain.AjaxResult;
import com.myzl.common.core.redis.RedisCache;
import com.myzl.common.enums.DemoEnum;
import com.myzl.common.enums.PictureRecognitionEnum;
import com.myzl.common.utils.StringUtils;
import com.myzl.common.utils.file.FileHandleUtils;
import com.myzl.common.utils.sign.Base64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author Administrator
 */
@Service
@Slf4j(topic = "admin-user")
public class AiShowServiceImpl implements AiShowService {

    @Autowired
    private ImageRecognitionConfig imageRecognitionConfig;
    @Autowired
    private IPythonService pythonService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private DemoService demoService;


    @Override
    public AjaxResult getImages() {
        List<String> fileNames = FileHandleUtils.getOnlyFileNames(imageRecognitionConfig.getImage_path());
        if (!fileNames.isEmpty()) {
            FileReader fileReader = new FileReader(imageRecognitionConfig.getImage_path() + fileNames.get(0));
            byte[] bytes = fileReader.readBytes();
            String encode = Base64.encode(bytes);
            return AjaxResult.success(fileNames).put("image",encode);
        }
        return AjaxResult.warn("该“"+imageRecognitionConfig.getImage_path()+"”路径下无图片文件，请检查改路径下是否存在图片文件");
    }

    @Override
    public AjaxResult getImage(Integer index) {
        List<String> fileNames = FileHandleUtils.getOnlyFileNames(imageRecognitionConfig.getImage_path());
        if (!fileNames.isEmpty() && index < fileNames.size()) {
            FileReader fileReader = new FileReader(imageRecognitionConfig.getImage_path() + fileNames.get(index));
            byte[] bytes = fileReader.readBytes();
            String encode = Base64.encode(bytes);
            return AjaxResult.success(encode);
        }
        return AjaxResult.warn("该“"+index+"”索引下无图片");
    }

    @Override
    public AjaxResult aiRecognition(Integer index) {
        Map<String,Object> result = new HashMap<>();
        List<String> fileNames = FileHandleUtils.getOnlyFileNames(imageRecognitionConfig.getImage_path());
        if (!fileNames.isEmpty() && index < fileNames.size()) {
            String inputFileName = imageRecognitionConfig.getImage_path() + fileNames.get(index);
            String outputFileName = imageRecognitionConfig.getImage_correct_path() + fileNames.get(index);
            String s = pythonService.imageCorrect(inputFileName, "[[320,210],[1920,110],[0,1080],[1900,950]]", "1002", outputFileName);
            log.info("矫正结果：{}",s);
            List<JSONObject> results = pythonService.imageTest(Collections.singletonList(outputFileName));
            if (!Objects.isNull(results) && !results.isEmpty()) {
                BigDecimal zero = new BigDecimal("0");
                JSONObject jsonObject = results.get(0);
                BigDecimal lumpCoal = jsonObject.getBigDecimal(PictureRecognitionEnum.LUMP_COAL.getSign());
                BigDecimal slack = jsonObject.getBigDecimal(PictureRecognitionEnum.SLACK.getSign());
                BigDecimal sieve = jsonObject.getBigDecimal(PictureRecognitionEnum.SIEVE.getSign());
                BigDecimal other = jsonObject.getBigDecimal(PictureRecognitionEnum.OTHER.getSign());
                lumpCoal = StringUtils.isNotNull(lumpCoal) ? lumpCoal : zero;
                slack = StringUtils.isNotNull(slack) ? slack : zero;
                sieve = StringUtils.isNotNull(sieve) ? sieve : zero;
                other = StringUtils.isNotNull(other) ? other : zero;
                result.put("lumpCoal",lumpCoal.intValue());
                result.put("slack",slack.intValue());
                result.put("sieve",sieve.intValue());
                result.put("other",other.intValue());
                if (slack.compareTo(zero) == 0){
                    result.put("slackProportion",zero.intValue());
                    result.put("coalProportion",zero.intValue());
                } else {
                    BigDecimal slackProportion = slack.divide(slack.add(lumpCoal), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                    result.put("slackProportion",slackProportion.intValue());
                    BigDecimal coalProportion = slack.add(lumpCoal).divide(slack.add(lumpCoal).add(sieve), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                    result.put("coalProportion",coalProportion.intValue());
                }
                if (sieve.compareTo(zero) == 0){
                    result.put("sieveProportion",zero.intValue());
                } else {
                    BigDecimal sieveProportion = sieve.divide(slack.add(lumpCoal).add(sieve), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                    result.put("sieveProportion",sieveProportion.intValue());
                }
            }
        }
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult aiIdentify() {
        boolean redisPoliceFlag = demoService.getRedisPoliceFlag(DemoEnum.efficiency);
        List<String> fileNames = FileHandleUtils.getOnlyFileNames(imageRecognitionConfig.getImage_path());
        log.info("fileNames:{}",fileNames.size());
        String basePath = imageRecognitionConfig.getImage_path();
        if (redisPoliceFlag) {
            fileNames = FileHandleUtils.getOnlyFileNames(imageRecognitionConfig.getImage_warn_path());
            basePath = imageRecognitionConfig.getImage_warn_path();
            log.info("efficiency fileNames:{}",fileNames.size());
        }
        Integer size = redisCache.getCacheObject(getCacheKey("size"));
        Integer index = redisCache.getCacheObject(getCacheKey("index"));
        String fileName = "";
        if (fileNames.isEmpty()){
            log.info("文件夹为空");
            return AjaxResult.success();
        }
        if (Objects.isNull(size)){
            size = fileNames.size();
            index = 0;
            redisCache.setCacheObject(getCacheKey("size"),fileNames.size());
        }
        if (!size.equals(fileNames.size())){
            redisCache.setCacheObject(getCacheKey("size"),fileNames.size());
            index = 0;
            fileName = fileNames.get(0);
            log.info("size true {}",size);
            log.info("index true {}",index);
        } else {
            index ++;
            if (index.compareTo(size) >= 0){
                index = 0;
            }
            fileName = fileNames.get(index);
            log.info("size false {}",size);
            log.info("index false {}",index);
        }
        redisCache.setCacheObject(getCacheKey("index"),index);
        // 图片识别
        String outputFileName = basePath + fileName;
        pythonService.invokePrediction(Collections.singletonList(outputFileName));
        return AjaxResult.success();
    }

    /**
     * 设置cache key
     *
     * @param key 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String key)
    {
        return CacheConstants.AI_KEY + key;
    }
}
